package com.samehope.ar.socket.strategy.impl;

import com.samehope.ar.entity.Device;
import com.samehope.ar.entity.SysUser;
import com.samehope.ar.socket.annotation.Command;
import com.samehope.ar.socket.constant.CommandEnum;
import com.samehope.ar.socket.handler.HttpRequestHandler;
import com.samehope.ar.socket.strategy.CommandHandleStrategy;
import com.samehope.ar.socket.support.MessageBody;
import com.samehope.ar.socket.support.NettyContext;
import io.netty.channel.Channel;

/**
 * @Description: 用于连接设备的指令处理
 * @Author: ZhangLuo
 * @Email: 1946430@qq.com
 */
@Command(value = CommandEnum.CONNECT_DEVICE)
public class ConnectDeviceHandleStrategyImpl implements CommandHandleStrategy {

    @Override
    public void handle(MessageBody messageBody, Channel channel) {

        // 获取设备码, 按照规范, 连接设备指令的body应该存放 目标设备码 mac
        String deviceMac = String.valueOf(messageBody.getBody());

        // 判断当前 channel 有没有绑定设备
        if (channel.hasAttr(HttpRequestHandler.DEVICE)) {
            NettyContext.writeMsg(channel, MessageBody.of(CommandEnum.ERROR, "已有连接, 请先断开当前设备连接").toString());
            return;
        }

        // 获取临时预连接设备里的设备通道 并 判空
        Channel deviceChannel = NettyContext.getTempChannel(deviceMac);
        if (deviceChannel == null) {
            NettyContext.writeMsg(channel, MessageBody.of(CommandEnum.ERROR, "当前设备不在线或已被其他用户连接").toString());
            return;
        }

        // 设置设备正式连接
        NettyContext.setConnectedDevice(deviceMac);

        // 获取手机终端连接的用户信息 和 令牌信息 并绑定到设备的连接上
        SysUser user = channel.attr(HttpRequestHandler.USER).get();
        String token  = channel.attr(HttpRequestHandler.TOKEN).get();

        deviceChannel.attr(HttpRequestHandler.USER).set(user);
        deviceChannel.attr(HttpRequestHandler.TOKEN).set(token);

        // 获取设备信息并绑定到用户的连接上
        Device device = deviceChannel.attr(HttpRequestHandler.DEVICE).get();

        channel.attr(HttpRequestHandler.DEVICE).set(device);

        // 连接成功, 返回响应
        NettyContext.writeMsg(channel, messageBody.toString());
    }
}
